if($.amud==null)
	$.amud={};
$.amud.core={
	server_debug:false,
	response_debug:false,
	user:{
			id:null,
			charId:null,
			HP:null,
			MP:null,
			XP:null,
			commands:{
			}
	},
	password:'',
	key:'',
	intervalId:'',
	intervalDelay:5000,
	time:Math.round(new Date().getTime() / 1000),
	name:null,
    loginBox:null,
    signupBox:null,
    autoRefresh:false,
    waiting:false,
    requestList:'',
	url:'amud.php',
    help:'<span class="help_title">AMUD</span>',
	currentHelp:'',
	auth:function(name,password){
		this.name=name;
		this.password=password;
		this.post($.amud.core.processAuth,'login;look');
	},
    newAccount:function(name,password,email,character){
        this.name=name;
		this.password=password;
        this.refreshKey();
        $.post( $.amud.core.url,
                {   key:this.key,
                    id:this.name,
                    time:this.time,
                    debug:this.server_debug,
                    signup:'true',
                    'password':password,
                    'email':email,
                    'character':character,
                    'command':'login;look'},
                $.amud.core.processAuth);
    },
	refreshKey:function(){
        var t = Math.round(new Date().getTime() / 1000);
        var old = this.time;
        
        if(old>=t){
            this.time++;
        }else{
            this.time = t;
        }

        //$.wterm_methods.add('<div class="amud_error_message">Refreshing old time is '+old+' new time is '+this.time+'</div>');

		this.key = sha1Hash(this.name+this.password+this.time);
	},
	closeAuth:function(){
		$.modal.close();
		$("#amudLoginBox").css('display','none');
        $("#signupBox").css('display','none');
		$("#wterm_input").focus();
	},
	post:function(callback,command){
        if($.amud.core.waiting){
            if(command!=''){
                $.amud.core.requestList+=';'+command;
            }
        }else{
            $.amud.core.waiting=true;
            this.refreshKey();
            if($.amud.core.requestList!=''){
                command=$.amud.core.requestList+';'+command;
                $.amud.core.requestList='';
            }
    		$.post($.amud.core.url,{key:this.key,id:this.name,time:this.time,debug:this.server_debug,'command':command},callback);
        }
	},
    processAuth:function(response, text_status){
								$.wterm_methods.clear();
								$.amud.core.closeAuth();
								$.amud.core.process(response, text_status);
								},
	process:function( data, text_status ){
        $.amud.core.waiting=false;
        if($.amud.core.requestList!=''){
            $.amud.core.post($.amud.core.process,'');
        }
        if(isObject(data)){
            response=data;
        }else{
            try{
                response=JSON.parse(data);
            }catch(exception){
                response = eval('(' + data + ')');
            }
        }
        if($.amud.core.response_debug){
			$.wterm_methods.add('<div class="amud_debug_message">'+JSON.stringify(data)+'</div>');
		}

		if(response!=null && response.user!=null){
			$.amud.core.user.id=response.user.id;
			$.amud.core.setPrompt(response.user);
			$.amud.core.user=response.user;
			if($.amud.core.sizeOf(response.user.commands)>0){
				$.wterm_methods.clear_commands();
				$.amud.core.register();
				$(document).trigger('login'); 
			}
		}else if(response==null){
            $.wterm_methods.add('<div class="amud_error_message">'+text_status+'</div>');
        }else{
            //we have an response, but there is no user
            //probably an autentication error
        }
		for ( var i in response.errors ){
		    $.wterm_methods.add('<div class="amud_error_message">'+$.amud.msg.toHtml(response.errors[i])+'</div>');
		}
		for ( i in response.debug ){
		    $.wterm_methods.add('<div class="amud_debug_message">'+$.amud.msg.toHtml(response.debug[i])+'</div>');
		}
		for ( i in response.messages ){
		    $.wterm_methods.add('<div class="amud_character_message">'+$.amud.msg.toHtml(response.messages[i])+'</div>');
		}
   		$(document).trigger('updated');
	},
	addAmudLoginBox:function(){
    	$('body').append('<div id="amudLoginBox">'
    					+'	<span id="amudLoginBoxTitle">Authentication</span><br />'
    					+'	<form onsubmit="javascript:$.amud.core.auth(this.amudLogin.value,this.amudPassword.value);return false;">'
    					+'		<label for="login">Login</label>'
    					+'		<input type="text" name="login" id="amudLogin" /><br />'
    					+'		<label for="password">Password</label>'
    					+'		<input type="password" name="password" id="amudPassword" /><br />'
    					+'		<input id="amudLoginSubmit" value="Enter" type="submit" />'
    					+'	</form>'
    					+'</div>');
	},
    addSignupBox:function(){
    	$('body').append('<div id="signupBox">'
    					+'	<span id="signupBoxTitle">New Account</span><br />'
    					+'	<form onsubmit="javascript:$.amud.core.newAccount(this.signupLogin.value,this.signupPassword.value,this.signupEmail.value,this.signupCharacter.value);return false;">'
    					+'		<label for="login">Login</label>'
    					+'		<input type="text" name="login" id="signupLogin" /><br />'
    					+'		<label for="password">Password</label>'
    					+'		<input type="password" name="password" id="signupPassword" /><br />'
                        +'		<label for="email">e-mail</label>'
    					+'		<input type="email" name="email" id="signupEmail" /><br />'
    					+'		<label for="character">Character name</label>'
                        +'		<input type="character" name="character" id="signupCharacter" /><br />'
    					+'		<input id="signupSubmit" value="Sign up" type="submit" />'
    					+'	</form>'
    					+'</div>');
	},
	method:function(){
        $.wterm_methods.prompt("&gt; ");
        $.amud.core.user.commands=[];
        $.wterm_methods.clear_commands();
        $.amud.core.register();
		$.amud.core.user.id=null;
		if($.amud.core.loginBox==null){
			$.amud.core.addAmudLoginBox();
			$.amud.core.loginBox=$("#amudLoginBox");
		}	
		$("#amudLoginBox").modal({opacity:100,onOpen: function (dialog) {
															dialog.overlay.fadeIn(0, function () {
																				dialog.container.fadeIn(0, function () {
																						dialog.data.fadeIn(0,function () {
																							$("#amudLogin").attr('value','');
																							$("#amudPassword").attr('value','');	
																							$("#amudLogin").focus();
																							});
																						});
																				});
															}});
	},
    signup:function(){
        if($.amud.core.signupBox==null){
			$.amud.core.addSignupBox();
			$.amud.core.signupBox=$("#signupBox");
		}
		$("#signupBox").modal({opacity:100,onOpen: function (dialog) {
															dialog.overlay.fadeIn(0, function () {
																				dialog.container.fadeIn(0, function () {
																						dialog.data.fadeIn(0,function () {
																							$("#signupLogin").attr('value','');
																							$("#signupPassword").attr('value','');
                                                                                            $("#signupEmail").attr('value','');
																							$("#signupLogin").focus();
																							});
																						});
																				});
															}});
    },
	setPrompt:function(user){
		$.wterm_methods.prompt(	"<span class='charId'>"+user.charId+"</span>"+
								"<span class='hp'>HP:"+user.HP+"</span>"+
								"<span class='mp'>MP:"+user.MP+"</span>"+
								"<span class='xp'>XP:"+user.XP+"</span>"+'&gt;');
	},
	autoRefreshOn:function(){
        if(!$.amud.core.autoRefresh){
            $.amud.core.autoRefresh=true;
            clearInterval($.amud.core.intervalId);
            $.amud.core.intervalId=setInterval(function(){
											if($.amud.core.user.id!=null){
												$.amud.core.post($.amud.core.process,"");
											}
										}, $.amud.core.intervalDelay);
        }
	},
	autoRefreshOff:function(){
        $.amud.core.autoRefresh=false;
		clearInterval($.amud.core.intervalId);
	},
	sizeOf:function(obj) {
							var len = obj.length ? --obj.length : -1;
							for (var k in obj)
                                len++;
							return len;
	},
	register:function(){
		$.amud.core.currentHelp=$.amud.core.help;
 	    
		for(var index in $.amud.core.user.commands){
		  $.register_command(index,function(token){$.amud.core.post($.amud.core.process,token)});
		  $.amud.core.currentHelp=	$.amud.core.currentHelp+'<br /><span class="help_command">'+index+'</span>'+
		  							'<span class="help_description">'+$.amud.core.user.commands[index]+'</span>';
		}

 	    $.amud.core.currentHelp=$.amud.core.currentHelp+'<br /><span class="help_command">help</span><span class="help_description">(local)show this help</span>';
 	    $.amud.core.currentHelp=$.amud.core.currentHelp+'<br /><span class="help_command">clear</span><span class="help_description">(local) clean the screen</span>';

   	    $.register_command('login',$.amud.core.method);
 	    $.amud.core.currentHelp=$.amud.core.currentHelp+'<br /><span class="help_command">login</span><span class="help_description">(local) open the login box</span>';
 	    
 	    $.register_command('teste',$.amud.core.teste);
 	    
		$.amud.core.currentHelp=$.amud.core.currentHelp+'<br />';
    	$.register_command( 'help', function() {
    		return $.amud.core.currentHelp;
      	});
	},
	addCommand:function(cmd,func,msg){
	    $.register_command(cmd,func);
		$.amud.core.currentHelp=$.amud.core.currentHelp+msg+'<br />';
	}
}
function isNumber(o)	{return parseInt(o) != NaN && parseInt(o) == o}
function isArray(o) 	{return isObject(o) && o.constructor == Array}  
function isObject(o) 	{return o && "object" == typeof o}